<template>
  <div class="address-picker">
    <el-input
      v-model="displayAddress"
      placeholder="请选择地址"
      readonly
      @click="openMapModal"
      class="address-input"
    >
      <template #prefix>
        <Icon icon="ep:location" width="16" height="16" style="margin-top: 4px; color: #999;" />
      </template>
    </el-input>
  </div>

  <!-- 地图弹窗 -->
  <el-dialog v-model="isModalVisible" title="请选择位置" width="75%" :before-close="closeModal">
    <div class="map-wrapper">
      <div id="container" class="map-container"></div>
      <div v-if="loading" class="map-loading">地图加载中，请稍候...</div>
    </div>
    <div class="selected-address">
      已选地址：{{ selectedLocation.address }}
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeModal">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue'])

// 当前地址信息
const selectedLocation = ref({
  address: '',
  longitude: '',
  latitude: ''
})

// 显示在输入框中的地址（计算属性）
const displayAddress = computed(() => selectedLocation.value.address || '请选择地址')

// 弹窗状态 & 加载状态
const isModalVisible = ref(false)
const loading = ref(true)

// 设置默认地址：诸城市
function setDefaultLocation() {
  selectedLocation.value = {
    address: '山东盛途互联网科技',
    longitude: '119.4243',
    latitude: '36.03409'
  }
}

// 解析初始值（仅当有传入值时才解析）
function parseInitialValue(value) {
  try {
    const parsed = JSON.parse(value)
    if (parsed && parsed.longitude && parsed.latitude) {
      selectedLocation.value = {
        address: parsed.address || '',
        longitude: parsed.longitude,
        latitude: parsed.latitude
      }
    } else {
      selectedLocation.value = {
        address: '',
        longitude: '',
        latitude: ''
      }
    }
  } catch (e) {
    selectedLocation.value = {
      address: '',
      longitude: '',
      latitude: ''
    }
  }
}

// 监听 modelValue 变化，自动刷新地址
watch(
  () => props.modelValue,
  (newVal) => {
    parseInitialValue(newVal)
  },
  {
    immediate: true
  }
)

// 打开地图弹窗
function openMapModal() {
  // 如果当前没有选中的地址，就默认设置为诸城
  if (!selectedLocation.value.address) {
    setDefaultLocation()
  }

  isModalVisible.value = true
  nextTick(() => {
    initMap()
  })
}

// 关闭弹窗并销毁地图实例
function closeModal() {
  isModalVisible.value = false
  emit('update:modelValue', JSON.stringify(selectedLocation.value))

  // 销毁地图实例
  if (window.AMap && map) {
    map.destroy()
    map = null
  }
}

// 高德地图对象
let map = null

// 初始化地图
async function initMap() {
  loading.value = true

  if (!window.AMap && !map) {
    window._AMapSecurityConfig = {
      securityJsCode: '8cc27bd2e46ee79516ad3ebbf9ae722f'
    }

    AMapLoader.load({
      key: 'dbf4f4d8b64fb2813a0cdebe82c122e4',
      version: '2.0',
      plugins: ['AMap.Geocoder']
    })
      .then((AMap) => {
        map = new AMap.Map('container')
        initLocation(AMap)
      })
      .catch((e) => {
        console.error('高德地图加载失败:', e)
        loading.value = false
      })
  } else {
    // 如果已经加载过，重新创建地图实例
    try {
      map = new AMap.Map('container')
      initLocation()
    } catch (e) {
      console.error('地图重新初始化失败:', e)
      loading.value = false
    }
  }
}

// 设置地图定位
function initLocation(AMapInstance) {
  let lng, lat

  if (selectedLocation.value.longitude && selectedLocation.value.latitude) {
    lng = parseFloat(selectedLocation.value.longitude)
    lat = parseFloat(selectedLocation.value.latitude)
  } else {
    setDefaultLocation()
    lng = parseFloat(selectedLocation.value.longitude)
    lat = parseFloat(selectedLocation.value.latitude)
  }

  const geocoder = new AMap.Geocoder()

  geocoder.getAddress([lng, lat], (status, result) => {
    if (status === 'complete' && result.regeocode) {
      selectedLocation.value.address = result.regeocode.formattedAddress
    }

    map.clearMap()
    new AMap.Marker({
      position: new AMap.LngLat(lng, lat),
      title: selectedLocation.value.address
    }).setMap(map)

    map.setZoomAndCenter(15, [lng, lat])
    loading.value = false
  })

  map.off('click') // 避免重复绑定
  map.on('click', function (e) {
    const clickLng = e.lnglat.getLng()
    const clickLat = e.lnglat.getLat()

    geocoder.getAddress([clickLng, clickLat], (status, result) => {
      if (status === 'complete' && result.regeocode) {
        const address = result.regeocode.formattedAddress
        selectedLocation.value = {
          address,
          longitude: clickLng.toFixed(6),
          latitude: clickLat.toFixed(6)
        }

        map.clearMap()
        new AMap.Marker({
          position: new AMap.LngLat(clickLng, clickLat),
          title: address
        }).setMap(map)

        map.setZoomAndCenter(15, [clickLng, clickLat])
      }
    })
  })
}
</script>

<style scoped>
.address-picker {
  margin-bottom: 10px;
}

.map-wrapper {
  position: relative;
  height: 500px;
}

.map-container {
  height: 100%;
  border: 1px solid #e4e4e4;
  border-radius: 6px;
}

.map-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(255, 255, 255, 0.8);
  padding: 12px 20px;
  font-size: 14px;
  color: #666;
  border-radius: 4px;
  z-index: 999;
}

.selected-address {
  margin-top: 12px;
  font-size: 14px;
  color: #333;
}

.dialog-footer {
  text-align: right;
}

/* 输入框样式优化 */
.address-input {
  width: 100%;
  max-width: 100%;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.address-input:hover,
.address-input:focus {
  border-color: #165dff;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.3);
}

.address-input .el-input__inner {
  padding-left: 35px;
  height: 40px;
  line-height: 40px;
  border: 1px solid #dcdfe6;
  color: #333;
  font-size: 14px;
}

.address-input .el-input__inner::placeholder {
  color: #aaa;
  font-style: italic;
}

.address-input .el-input__prefix {
  left: 10px;
  top: 5px;
  color: #999;
}
</style>
